﻿using AutoMapper;
using Inventorycount.API.Write.Application.Command;
using Inventorycount.Domain;
using Inventorycount.ErrorCode;
using Inventorycount.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SqlSugar;
using System.Data;

namespace Inventorycount.API.Write.Application.CommandHandLer
{
    public class AddTransferCommandHandLer : IRequestHandler<AddTransferCommand, APIResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly ILogger<AddTransferCommandHandLer> _logger;
        private readonly SqlSugarHelp<Wms_Transfer_detail> _detailService;
        private readonly SqlSugarHelp<Wms_Transfer_order> _orderService;
        private readonly SqlSugarHelp<Wms_Operation_log> _logService;
        private readonly SqlSugarHelp<Wms_outbound_detail> _outboundDetailService;
        private readonly SqlSugarHelp<Wms_outbound_order> _outboundOrderService;
        private readonly SqlSugarHelp<Wms_inbound_order> _inboundOrderService;
        private readonly SqlSugarHelp<Wms_Inbound_record> _inboundRecordService;

        public AddTransferCommandHandLer(
            SqlSugarHelp<Wms_Transfer_detail> detailService,
            SqlSugarHelp<Wms_Transfer_order> orderService,
            SqlSugarHelp<Wms_Operation_log> logService,
            SqlSugarHelp<Wms_outbound_detail> outboundDetailService,
            SqlSugarHelp<Wms_outbound_order> outboundOrderService,
            SqlSugarHelp<Wms_inbound_order> inboundOrderService,
            SqlSugarHelp<Wms_Inbound_record> inboundRecordService,
            IMapper mapper,
            ILogger<AddTransferCommandHandLer> logger)
        {
            _detailService = detailService;
            _orderService = orderService;
            _logService = logService;
            _outboundDetailService = outboundDetailService;
            _outboundOrderService = outboundOrderService;
            _inboundOrderService = inboundOrderService;
            _inboundRecordService = inboundRecordService;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddTransferCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();

            try
            {
                // 1. 检查调拨单号是否已存在
                var exists = await _orderService.SqlSugarClient.Queryable<Wms_Transfer_order>()
                    .Where(x => x.Transfer_no == request.Transfer_no && !x.IsDeleted)
                    .AnyAsync();

                if (exists)
                {
                    result.Code = ResultCode.Fail;
                    result.Message = "调拨单号已存在";
                    return result;
                }

                // 2. 映射主表和明细表数据
                var transferOrder = _mapper.Map<Wms_Transfer_order>(request);
                transferOrder.Status = 1; // 待审核状态
                transferOrder.AddDateTime = DateTime.Now;

                var transferDetails = _mapper.Map<List<Wms_Transfer_detail>>(request.Detail);
                transferDetails.ForEach(d => {
                    d.outbound_status = 0; // 未出库
                    d.inbound_status = 0;  // 未入库
                });

                // 3. 使用事务执行所有操作
                var transactionResult = await _orderService.SqlSugarClient.Ado.UseTranAsync(async () =>
                {
                    // 3.1 添加调拨主表
                    var transferId = await _orderService.InsertReturnIdentityAsync(transferOrder);

                    // 3.2 添加调拨明细
                    transferDetails.ForEach(d => d.Transfer_id = transferId);
                    await _detailService.InsertRangeAsync(transferDetails);

                    // 3.3 创建出库单（待审批）
                    var outboundOrder = new Wms_outbound_order
                    {
                        Outbound_code = $"OUT_{request.Transfer_no}",
                        Transfer_id = transferId,
                        Warehouse_id = request.Out_warehouse_id,
                        Status = 0, // 待出库
                        Operator_id = request.Operator_id,
                        Operate_time = DateTime.Now,
                        Remark = $"调拨出库-{request.Transfer_no}"
                    };
                    var outboundId = await _outboundOrderService.InsertReturnIdentityAsync(outboundOrder);

                    // 3.4 创建出库明细（待审批）
                    var outboundDetails = transferDetails.Select(d => new Wms_outbound_detail
                    {
                        Outbound_id = outboundId,
                        Goods_id = d.Goods_id,
                        Quantity = d.Quantity,
                        Price = d.Price,
                        Status = 0, // 待出库
                        Transfer_id = d.Transfer_id,
                        Operator_id = request.Operator_id,
                        Create_time = DateTime.Now,
                        Remark = $"调拨出库-{request.Transfer_no}"
                    }).ToList();
                    await _outboundDetailService.SqlSugarClient.Insertable(outboundDetails).ExecuteCommandAsync();

                    // 3.5 创建入库单（待审批）
                    var inboundOrder = new Wms_inbound_order
                    {
                        Inbound_code = $"IN_{request.Transfer_no}",
                        Transfer_id = transferId,
                        Warehouse_id = request.In_warehouse_id,
                        Status = 0, // 待入库
                        Operator_id = request.Operator_id,
                        Operate_time = DateTime.Now,
                        Remark = $"调拨入库-{request.Transfer_no}"
                    };
                    var inboundId = await _inboundOrderService.InsertReturnIdentityAsync(inboundOrder);

                    // 3.6 创建入库明细（待审批）
                    var inboundDetails = transferDetails.Select(d => new Wms_Inbound_record
                    {
                        Inbound_id = inboundId,
                        Goods_id = d.Goods_id,
                        Quantity = d.Quantity,
                        Price = d.Price,
                        Status = 0, // 待入库
                        Transfer_id = d.Transfer_id,
                        Create_time = DateTime.Now,
                        Operator_id = request.Operator_id,
                        Remark = $"调拨入库-{request.Transfer_no}"
                    }).ToList();
                    await _inboundRecordService.SqlSugarClient.Insertable(inboundDetails).ExecuteCommandAsync();

                    // 3.7 记录操作日志
                    var log = new Wms_Operation_log
                    {
                        Transfer_id = transferId,
                        Operation_type = "添加调拨单",
                        operator_id = request.Operator_id,
                        Operation_desc = $"创建调拨单[{request.Transfer_no}]，调出仓库:{request.Out_warehouse_id}，调入仓库:{request.In_warehouse_id}",
                        operation_time = DateTime.Now
                    };
                    await _logService.AddAsync(log);

                    return transferId;
                });

                if (transactionResult.IsSuccess)
                {
                    result.Code = ResultCode.Ok;
                    result.Message = "调拨单添加成功，等待审批";
                    result.Data = transactionResult.Data;
                }
                else
                {
                    result.Code = ResultCode.Fail;
                    result.Message = $"调拨单添加失败: {transactionResult.ErrorMessage}";
                    _logger.LogError(transactionResult.ErrorException, "添加调拨单事务失败");
                }
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = "添加调拨单时发生系统错误";
                _logger.LogError(ex, "添加调拨单异常");
            }

            return result;
        }
    }
}